package com.atguigu.gmall.common.util;
import javassist.bytecode.stackmap.TypeData;
import org.csource.common.MyException;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import java.io.IOException;
/**
 * 文件上传工具类
 * @author 冇有
 * @since 2021-09-17
 */
public class FaseDfsUtil {
    private  static StorageClient1 storageClient1 = null;
static{
    //传入参数 配置文件的绝对路径
    String path = TypeData.ClassName.class.getClassLoader().getResource("tracker.conf").getPath();
    try {
        ClientGlobal.init(path);
        //首先连接跟踪器
        TrackerClient trackerClient = new TrackerClient();
        //获取到了存储节点的 ip地址
        TrackerServer connection = trackerClient.getConnection();
        //连接存储节点
         storageClient1 = new StorageClient1();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

    /**
     *
     * @param files 文件转换为字节数组
     * @param exe  文件后缀名
     * @return
     */
    public static String uplodeFile(byte[]files,String exe){
        String fileId=null;
        try {
            fileId = storageClient1.upload_appender_file1(files, exe, null);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return fileId;
    }

    /**
     * 删除方法
     * @param fileId 存在存储节点的文件ID
     */
    public static void deleteFile(String fileId){
        try {
            storageClient1.delete_file1(fileId);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载文件方法
     * @param fileId 存在存储节点的文件ID
     * @return
     */
    public static byte[] downloadFile(String fileId){
        byte [] fileBytes = null;
        try {
           fileBytes = storageClient1.download_file1(fileId);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }
        return fileBytes;
    }
}
